package org.mineground.handlers;

import java.io.*;
import java.util.*;
import org.bukkit.ChatColor;
import org.jibble.pircbot.Colors;
import org.mineground.Main;
import org.mineground.Utilities;
import org.mineground.player.MinegroundPlayer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @file RandomMessageSender.java (2012)
 * @author Daniel Koenen
 * 
 */
public class RandomMessageSender {
    private static final Logger ExceptionLogger = LoggerFactory.getLogger(RandomMessageSender.class);
    
    private List<String> announcedMessages;
    private File configurationFile;
    private Timer messageTimer;
    private Random randomManager;
    
    public RandomMessageSender() {
        announcedMessages = new ArrayList<String>();
        configurationFile = new File(Main.getInstance().getDataFolder(), "randomMessages.txt");
        randomManager = new Random();
        
        initializeMessages();
        callTimer();
    }
    
    private void initializeMessages() {
        try {
            FileInputStream fileStream = new FileInputStream(configurationFile);
            DataInputStream dataStream = new DataInputStream(fileStream);
            InputStreamReader streamReader = new InputStreamReader(dataStream);
            BufferedReader configurationReader = new BufferedReader(streamReader);
            String nextLine;
            
            while ((nextLine = configurationReader.readLine()) != null) {
                announcedMessages.add(nextLine);
            }
        }
        
        catch (Exception exception) {
            ExceptionLogger.error("Exception caught", exception);
        }
    }
    
    private void callTimer() {
	if (messageTimer != null) {
	    messageTimer.cancel();
        }

	messageTimer = new Timer();
	messageTimer.schedule(new AnnouncedMessage(), Main.getInstance().getConfigHandler().announceMessageDelay * 60000L);
    }
    
    public void reloadMessages() {
        announcedMessages = new ArrayList<String>();
        initializeMessages();
    }
    
    private class AnnouncedMessage extends TimerTask {
        @Override
        public void run() {
            int messageId = randomManager.nextInt(announcedMessages.size());
            
            Utilities.sendMessageToAll(ChatColor.DARK_AQUA + announcedMessages.get(messageId));
            Main.getInstance().getIRCHandler().sendMessage(Main.getInstance().getConfigHandler().ircChannel, Colors.PURPLE + announcedMessages.get(messageId));
            callTimer();
        }
    }
}
